package com.dhecp.project.business.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.ProductInfo;
import com.dhecp.project.business.service.ProductInfoService;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.common.controller.FoldRelationController;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.domain.SysDictionaryRelationForModule;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import com.dhecp.project.system.service.SysDictionaryRelationForModuleService;

/**
 * 产品信息 控制层
 * @author lwl
 * @version 2019年11月12日
 */
@Controller
@RequestMapping("/business/product")
public class ProductInfoController extends BaseModuleController{

	private String prefix = "business/product";
    private String moduleTable = ModuleTable.PRODUCT_INFO;
    
    @Autowired
    private ProductInfoService productInfoService;
    
    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;
    
    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

	@Autowired
    private SysDictionaryRelationForModuleService dictionaryRelationForModuleService;

	@Autowired
    private FoldRelationController foldRelationController;
	
    /**
     * 打开产品列表
     * @param 
     * @return ModelAndView
     * @author lwl
     */
	@RequiresPermissions("business:product:view")
    @GetMapping()
    public ModelAndView dataList(@RequestParam Map<String, Object> params)
    {
		params.put("moduleTable", moduleTable);
    	params.put("entity", new ProductInfo()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
    	Subject userSubject = ShiroUtils.getSubject();
    	Integer toolBarWidth = 0;
    	if (userSubject.isPermitted("business:product:delete")){	//当前登录用户主体是否有删除的权限
        	params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
        	toolBarWidth = toolBarWidth + 100;
    	}
    	if (userSubject.isPermitted("business:product:edit")){ //当前登录用户主体是否有修改的权限(暂不需要商品修改)
    		toolBarWidth = toolBarWidth + 0;
    	}
    	params.put("toolBarWidth", toolBarWidth);    	

    	Object importFields = null;    	
		ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        try{
        	importFields = dictionaryForFieldService.queryFieldFrontImport(params); //导入模板
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.addObject("importFields",importFields);				//导入字段模板
        mv.addObject("moduleTable", moduleTable);
        mv.setViewName(prefix + "/product");
		return mv;
    }
	
	/**
     * 打开产品选择页面
     * @param params
     * @return ModelAndView
     */
    @GetMapping("/select")
    public ModelAndView selectList(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
    	params.put("entity", new ProductInfo()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
    	params.put("toolBarWidth", 0);
    	if(params.get("pagetype") !=null && params.get("pagetype").toString().equalsIgnoreCase("checkbox"))params.put("checkBox", "yes");
        else params.put("radio", "yes");
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.addObject("prefix", prefix);
        mv.addObject("moduleTable", moduleTable);
        mv.setViewName("common/select");
        return mv;
    }
	
	/**
     * 查询所有产品信息
     * @param params
     * @return TableDataInfo
     * @author lwl
     */
	@GetMapping("/list")
    @RequiresPermissions("business:product:list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params)
    {
		params.put("moduleTable", moduleTable);
        List<ProductInfo> productlist = new ArrayList<ProductInfo>();
        try {
        	productlist = productInfoService.queryProductInfo(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());            
        }
        return getDataTable(productlist);
    }

	/**
	 * 匹配产品信息
	 * @param relationguid 必要参数：调入关系guid
	 * @param productInfoItems 必要参数：对应实体类的json格式字符串（包括：matchIid【必要，页面中行号】,gBrand,gID,gModel,gName,gSerial,gUnit）
	 * @return
	 * @author DH-Xxj
	 */
	@PostMapping("/matchlist")
    @ResponseBody
    public Map<String,Object> matchList(@RequestParam Map<String, Object> params){
		/*测试数据
		String productInfoItems = "[{\"matchIid\":\"1\",\"gID\":\"0522162\"},{\"matchIid\":\"2\",\"gID\":\"09B4041G08\"},{\"matchIid\":\"3\",\"gID\":\"1000102ZKLXXXXXXXXX\"},{\"matchIid\":\"4\",\"gID\":\"09B4041G08\"},{\"matchIid\":\"5\",\"gID\":\"09B4041G08\"},{\"matchIid\":\"6\",\"gID\":\"09B4041G08\"}]";
		params.put("productInfoItems", productInfoItems);
		*/
		params.put("moduleTable", moduleTable);
		Map<String,Object> returnData=new HashMap<String, Object>();
    	try {
			returnData.put("productlist", getDataTable(productInfoService.matchProductInfo(params)));
	        SysDictionaryRelationForModule relationForModule = dictionaryRelationForModuleService.queryDictionaryRelationForModuleByGuid(params.get("relationguid").toString());
        	returnData.put("foldRelation",foldRelationController.getRelationForField(params.get("relationguid").toString(), relationForModule));
		} catch (Exception e) {
			e.printStackTrace();
			returnData.put("productlist", getDataTable(this.getExceptionMessage(e).toString()));
			return returnData;
		}
        return returnData;
    }
	
	 /**
     * 导出产品信息
     * @param params
     * @return AjaxResult
     * @author lwl
	 * @throws Exception 
     */
    @Log(title = "产品导出", businessType = BusinessType.EXPORT)
    @RequiresPermissions("business:product:export")
    @GetMapping("/export")
    @ResponseBody
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception{
		params.put("moduleTable", moduleTable);
    	params.put("entity", new ProductInfo()); 
        List<ProductInfo> list = productInfoService.queryProductInfo(params);
//        ExcelUtil<ProductInfo> util = new ExcelUtil<ProductInfo>(ProductInfo.class);
    	params.put("getFieldAttributesType", "export");
    	List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<ProductInfo> util = new ExportExcelUtils<ProductInfo>(moduleTable,new ProductInfo());
        return util.exportExcel(list, fieldList, "产品数据", "export");
    }
    
    /**
     * 导出Excel导入模板
     * @param params
     * @return
     * @throws Exception
     * @author kimiloo
     */
    @RequiresPermissions("business:product:import")
    @Log(title = "产品数据导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exporttemplate")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult exportTemplate(@RequestParam Map<String, Object> params) throws Exception {
		params.put("moduleTable", moduleTable);
    	params.put("entity", new ProductInfo()); 
    	params.put("getFieldAttributesType", "template");

    	List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<ProductInfo> util = new ExportExcelUtils<ProductInfo>(moduleTable,new ProductInfo());
        return util.exportExcel(null, fieldList, "产品导入模板", "template");
    }
	
	/**
     * 打开新增产品信息息页面
     * @param params
     * @return ModelAndView
     * @author lwl
     */
    @RequiresPermissions("business:product:add")
    @GetMapping("/add")
    public ModelAndView add(@RequestParam Map<String, Object> params)
    {
    	params.put("moduleTable", moduleTable);
    	params.put("entity", new ProductInfo()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
    	params.put("readOnly", false);//开启生成列可编辑
    	params.put("toolBarWidth", 100);//限制操作区为100
    	params.put("getFieldAttributesType", "pageingrid");//pageingrid：网格字段
    	
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        try{
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("gridColumns",gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.addObject("pageType","add");
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.setViewName(prefix + "/product_add");
        return mv;
    }
    
    /**
     * 新增产品信息——数据提交
	 * @param productInfoItems
	 * @param fSl   面价（含税/未税）计算税率
	 * @param fType 面价（含税/未税）计算类型：（fType == 1：含税面价计算未税面价，fType == 0：未税面价计算含税面价）
     * @return AjaxResult
     * @author lwl
     */
    @Log(title = "产品保存", businessType = BusinessType.INSERT)
    @RequiresPermissions("business:product:add")
    @PostMapping("/addpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult addSave(@RequestParam Map<String, Object> params)
    {
    	AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= productInfoService.insertProduct(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 清理产品导入过渡表中遗留的数据
     * @param params 无需参数
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("business:product:add")
    @PostMapping("/cleanproductimportpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult cleanProductInfoImport(@RequestParam Map<String, Object> params)
    {
    	AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= productInfoService.cleanProductInfoImport(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 将本次导入的产品数据从产品导入过渡表中转入产品信息正式表
     * @param records 导入总记录数int类型
     * @return
     * @author DH-Xxj
     */
    @Log(title = "产品转移至正表", businessType = BusinessType.INSERT)
    @RequiresPermissions("business:product:add")
    @PostMapping("/importtoprocuctpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult importToProductInfo(@RequestParam Map<String, Object> params)
    {
    	AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= productInfoService.importToProductInfo(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     * 导入产品信息至产品信息过渡表——数据提交
	 * @param productInfoItems
	 * @param fSl   面价（含税/未税）计算税率
	 * @param fType 面价（含税/未税）计算类型：（fType == 1：含税面价计算未税面价，fType == 0：未税面价计算含税面价）
     * @return AjaxResult
     * @author kimiloo
     */
    @Log(title = "产品过渡表导入", businessType = BusinessType.INSERT)
    @RequiresPermissions("business:product:import")
    @PostMapping("/importpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult importSave(@RequestParam Map<String, Object> params)
    {
    	AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= productInfoService.importProduct(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     * 打开产品信息修改页面
     * @param params
     * @return ModelAndView
     * @author lwl
     */
    @RequiresPermissions("business:product:edit")
    @GetMapping("/edit")
    public ModelAndView menuInfoEdit(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        ProductInfo productInfo= new ProductInfo();
        mv = this.gotoModelAndViewErrorPage(params, "guid", "产品编号");
        if (mv.isEmpty()){
            try{
                dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
                if (dictionaryForFieldMap.isEmpty()){
                    ajaxResult = AjaxResult.error("未获取到字段属性。");
                }else{
                	productInfo = productInfoService.queryProductInfoByGuid(params.get("guid").toString());
                	if (productInfo == null){
                		ajaxResult = AjaxResult.error("没有查到菜单。");
                	}else{
                    	ajaxResult = AjaxResult.success("数据获取成功。");
                	}
                }
            }
            catch(Exception e){
                ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
            }
            mv.addObject("pageType","edit");
            mv.addObject("productInfo",productInfo);
            mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName(prefix + "/product_edit");
        }
        return mv;
    }
    
    /**
     * 修改产品信息--数据提交
     * @param params
     * @return AjaxResult
     * @author lwl
     */
    @Log(title = "产品修改", businessType = BusinessType.UPDATE)
    @RequiresPermissions("business:product:edit")
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editSave(@RequestParam Map<String, Object> params)
    {
    	AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= productInfoService.updateProduct(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     * 删除产品信息
     * @param params
     * @return AjaxResult
     * @author lwl
     */
    @RequiresPermissions("business:product:delete")
    @Log(title = "删除产品", businessType = BusinessType.DELETE)
    @PostMapping("/delete")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult productDelete(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= productInfoService.deleteProductInfoByGuid(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e)); 
        }
        return ajaxResult;
    }
}
